﻿using System.Collections.Generic;
using TestBat.IViewModels.Base;

namespace TestBat.ViewModels.Base
{
    public abstract class ComboBoxViewModel<VM, O> : ViewModel, IComboBoxViewModel<VM, O> where VM : IComboBoxItemViewModel<O>
    {
        public ComboBoxViewModel()
        {
            this.items = null;
            this.selectedItem = default(VM);
        }

        public IList<VM> Items
        {
            get
            {
                if (items == null)
                    Reset();

                return items;
            }
        }

        public event SelectionChangedEventHandler SelectionChanged;

        public VM SelectedItem
        {
            get
            {
                return selectedItem;
            }
            set
            {
                if (selectedItem == null || !selectedItem.Equals(value))
                {
                    selectedItem = value;
                    NotifyPropertyChanged(() => this.SelectedItem);

                    if (SelectionChanged != null)
                        SelectionChanged();
                }
            }
        }

        public void Reset()
        {
            items = new List<VM>();

            // add default
            var d = RecreateDefault();
            items.Add(d);
            SelectedItem = d;

            // add others
            var _items = RecreateItems();
            foreach (var i in _items)
                items.Add(i);

            NotifyPropertyChanged(() => this.Items);
        }

        protected abstract VM RecreateDefault();
        protected abstract IList<VM> RecreateItems();

        private IList<VM> items;
        private VM selectedItem;
    }
}
